<template>
  <div class="app-container">
    <local-loading :loading="loading"></local-loading>
    <div class="search-container">
      <el-form :inline="true">
        <el-form-item :label="$t('teacher.Kursart')">
          <el-select v-model="queryParams.courseType">
            <el-option
              v-for="dict in course_type_choose"
              :key="dict.value"
              :label="translateTagDictI18n('course_type_choose', dict.label)"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('teacher.Semester')">
          <el-select v-model="queryParams.semester">
            <el-option
              v-for="dict in semesters"
              :key="dict.value"
              :label="translateTagDictI18n('semesters', dict.label)"
              :value="dict.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="keywords" :label="$t('teacher.Kursname')">
          <el-input
            v-model="queryParams.keywords"
            :placeholder="$t('teacher.placeholder')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><el-icon style="margin-right: 5px; font-size: 18px">
              <Search /> </el-icon
            >{{ $t("teacher.Suche") }}</el-button
          >
          <el-button v-throttle="init" type=""
            ><el-icon style="margin-right: 5px; font-size: 18px">
              <Refresh /> </el-icon
            >{{ $t("teacher.Zurücksetzen") }}</el-button
          >
        </el-form-item>
        <el-form-item
          ><el-button
            v-throttle="openDialog"
            v-hasPerm="['course:teach:add']"
            type="success"
            ><el-icon> <CirclePlus /> </el-icon>&nbsp;
            {{ $t("teacher.Kurshinzufügen") }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-row v-if="CourseList?.length != 0" :gutter="30">
      <el-col v-for="(course, index) in CourseList" :key="index" :span="6">
        <el-card
          v-throttle="() => showCourseInfo(course.id)"
          class="box-card"
          :body-style="{ padding: '0px' }"
        >
          <el-image :src="course.wallpaperUrl" class="courseImage" />
          <div style="padding: 2px" class="msxx">
            <span style="font-weight: bold; font-size: 1.5rem">{{
              course.name
            }}</span>
            <div class="bottom clearfix yylc">
              <p style="font-size: 1.1rem; margin-top: 4px">
                {{ $t("teacher.Einheit") }}：{{ course.deptName }}
              </p>
              <p style="font-size: 1.1rem; margin-top: 4px">
                {{ $t("teacher.NamedesLehrers") }}：{{ course.leaderName }}
              </p>
              <p style="font-size: 1.1rem; margin-top: 4px">
                {{ $t("teacher.AssoziierterName") }}：{{
                  course.assistants.length == 0
                    ? $t("teacher.KeinLehrer")
                    : course.assistants.toString()
                }}
              </p>
              <p style="font-size: 1.1rem; margin-top: 4px">
                {{ $t("teacher.ProfessorKlasse") }}：{{
                  course.classes.length == 0
                    ? $t("teacher.KeineKlasse")
                    : course.classes.toString()
                }}
              </p>
              <p style="font-size: 1.1rem; margin-top: 4px">
                {{ $t("teacher.Startzeit") }}：{{ course.startTime }}
              </p>
              <!-- <p style="font-size: 1.1rem; margin-top: 4px">
                {{ $t("teacher.Endzeit") }}：{{ course.endTime }}
              </p> -->
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <empty-state v-else :name="'暂无课程'"></empty-state>

    <!-- 分页 -->
    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />
    <div v-draggable>
      <!--  新增课程表单 -->
      <el-dialog
        v-model="dialog.visible"
        :title="$t('teacher.Kurshinzufügen')"
        width="600px"
        @close="closeDialog"
      >
        <!-- 课程名 -->
        <el-form
          ref="coursenameFormRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
          label-position="left"
        >
          <el-form-item :label="$t('teacher.Kursname')" prop="name">
            <el-input
              v-model="formData.name"
              :placeholder="$t('teacher.placeholder')"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <!-- 学期 -->
          <el-form-item :label="$t('teacher.Semester')" prop="semester">
            <el-select id="submit-state" v-model="formData.semester">
              <el-option
                v-for="dict in semesters"
                :key="dict.value"
                :label="translateTagDictI18n('semesters', dict.label)"
                :value="dict.label"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">{{
              $t("teacher.bestätigen")
            }}</el-button>
            <el-button @click="closeDialog">{{
              $t("teacher.Abbrechen")
            }}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Teach",
  inheritAttrs: false,
});
import { AddCourse, getClassPage } from "@/api/course";
import { CourseForm, CoursePageVO, CourseQuery } from "@/api/course/types";
import LocalLoading from "@/components/LocalLoading/index.vue";
import EmptyState from "@/components/EmptyState/index.vue";
import { translateTagDictI18n } from "@/utils/i18n";
// 路由
import router from "@/router";
import { formatDate } from "@/utils/formatTime";
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();

// 字典
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 多个枚举
const { semesters, course_type_choose } = proxy?.useDict(
  "semesters",
  "course_type_choose"
);
const total = ref(0);
const CourseList = ref<CoursePageVO[]>();
const loading = ref(true);
// 获取弹窗表单
const coursenameFormRef = ref(ElForm); // 课程表单
// 弹窗组件
const dialog = reactive<DialogOption>({
  visible: false,
});
// 提交表单信息
const formData = reactive<CourseForm>({
  name: "",
  endTime: "",
  semester: "",
});
// 提交表单规则
const rules = reactive({
  name: [{ required: true, message: "课程名不能为空", trigger: "blur" }],
  endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
  semester: [{ required: true, message: "学期不能为空", trigger: "blur" }],
});
// 获取课程请求数据
const queryParams = reactive<CourseQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 搜索函数
function handleQuery() {
  getClassPage(queryParams)
    .then(({ data }) => {
      CourseList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
// 重置函数
function init() {
  queryParams.semester = "";
  queryParams.courseType = "" as never as number;
  queryParams.keywords = "";
  handleQuery(); // 重新获取分页数据
  ElMessage.success("重置成功");
}

/**
 * 打开新增课程弹窗
 */
function openDialog() {
  dialog.visible = true;
  dialog.title = "新增课程";
}
/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm(); // 重置表单
}

/**
 * 重置表单
 */
function resetForm() {
  formData.name = "";
}

/**
 * 表单提交
 * useThrottleFn 对于此次提交 做延迟处理
 */
const handleSubmit = useThrottleFn(() => {
  formData.endTime = formatDate(new Date(formData.endTime));
  coursenameFormRef.value.validate((valid: boolean) => {
    if (valid) {
      AddCourse(formData).then((res) => {
        handleQuery();
        ElMessage.success("添加课程成功!");
        // 关闭弹窗
        closeDialog();
      });
    }
  });
}, 3000);

function showCourseInfo(courseId: number) {
  let routeData = router.resolve({
    path: "/courseinfo",
    query: {
      courseId,
    },
  });
  window.open(routeData.href, "_blank");
}

// 监听当前路由的name变化
watch(
  () => router.currentRoute.value.name,
  (newRouterName: any, oldRouterName: any) => {
    if (oldRouterName === "Courseconfig" && newRouterName === "Teach") {
      handleQuery();
    }
  },
  { immediate: true }
);

onMounted(() => {
  handleQuery(); //首先查询
});

onActivated(() => {
  if (!userStore.codeId || userStore.codeId == "") {
    router.push("/me/personal").then(() => {
      ElMessage.warning("请先完善个人信息");
    });
  }
});
</script>

<style lang="scss" scoped>
.search-container {
  margin-top: 15px;
}

.addcourse {
  position: absolute;
  // width: 200px;
  /* 绝对定位，相对于最近的定位祖先元素 */
  // right: 50px;

  .el-icon {
    font-size: 16px;
  }
}

.msxx {
  font-size: 10px;
}

.box-card {
  border: 1px solid #ccc;
  /* 添加这一行 */
  border-radius: 10px;
  /* 添加这一行 */
  width: 23rem;
  padding: 16px 16px 8px 16px;
  /* 添加这一行 */
  // height: 225px;
  cursor: pointer;
  margin: 0 auto;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image {
  width: 100%;
  // height: 130px;
  border-radius: 10px;
  /* 添加这一行 */
}

.courseImage {
  width: 100%;
  border-radius: 6%;
  // height: 164px;
}

.el-card {
  margin: 20px auto;
  box-shadow: inset;
}

.yylc {
  p {
    padding: 0;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
}
</style>
